package com.rivues.module.manage.web.handler.system;

import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;


import com.rivues.core.RivuDataContext;
import com.rivues.module.platform.web.handler.Handler;
import com.rivues.module.platform.web.handler.ResponseData;
import com.rivues.module.platform.web.interceptor.LogIntercreptorHandler;
import com.rivues.module.platform.web.model.RivuSite;
import com.rivues.module.platform.web.model.SearchResultTemplet;
import com.rivues.util.RivuTools;
import com.rivues.util.local.LocalTools;
import com.rivues.util.mail.MailSender;
import com.rivues.util.tools.StringUtil;

@Controller
@RequestMapping("/{orgi}/manage/system/{service}")
public class SystemNoticeController extends Handler {

	private final Logger log = LoggerFactory
			.getLogger(LogIntercreptorHandler.class);

	@RequestMapping(value = "/rivusitesetting", name = "rivusitesetting", type = "manage", subtype = "system")
	public ModelAndView rivusitesetting(HttpServletRequest request,
			@PathVariable String orgi,@PathVariable String service) throws Exception {
		ModelAndView view = request(
				super.createManageTempletResponse("/pages/manage/system/rivusitesetting"),
				orgi);
		if(service.equals("sms")){
			view = request(
					super.createManageTempletResponse("/pages/manage/system/rivusitesmssetting"),
					orgi);
		}
		view.addObject("type",service);
		view.addObject("riveSiteList",super.getService().findAllByCriteria(
						DetachedCriteria.forClass(RivuSite.class)
						.add(Restrictions.eq("orgi", orgi))
						.add(Restrictions.eq("groupid", service))));
		return view;
	}
	
	@RequestMapping(value = "/rivusitesettingadd", name = "rivusitesettingadd", type = "manage", subtype = "system")
	public ModelAndView rivusitesettingadd(HttpServletRequest request,
			@PathVariable String orgi,@PathVariable String service) throws Exception{
		ResponseData responseData = new ResponseData("/pages/manage/system/rivusitesettingadd") ; 
		if(service.equals("sms")){
			responseData = new ResponseData("/pages/manage/system/rivusitesmssettingadd") ; 
		}
    	ModelAndView view = request(responseData , orgi);
		view.addObject("type",service);
		return view;
	}
	
	@RequestMapping(value = "/rivusitesettingaddo", name = "rivusitesettingaddo", type = "manage", subtype = "system")
	public ModelAndView rivusitesettingaddo(HttpServletRequest request,
			@PathVariable String orgi,@PathVariable String service,@Valid RivuSite rivusite) throws Exception {
		int count = super.getService().getCountByCriteria(
				DetachedCriteria.forClass(RivuSite.class)
						.add(Restrictions.eq("orgi", orgi)).add(Restrictions.eq("smtpuser", rivusite.getSmtpuser())));
		ResponseData response = new ResponseData(
				"redirect:/{orgi}/manage/system/{service}/rivusitesetting.html");
		if (count == 0) {
			rivusite.setOrgi(orgi);
			rivusite.setGroupid(service);
			if(rivusite.getSmtppassword() != null && rivusite.getSmtppassword() != ""){
				rivusite.setSmtppassword(RivuTools.encryption(rivusite.getSmtppassword()));
			}
			super.getService().saveIObject(rivusite);
			response = new ResponseData(
					"redirect:/{orgi}/manage/system/{service}/rivusitesetting.html?msgcode=I_MANAGE_70010001");
		} else {
			response = new ResponseData(
					"redirect:/{orgi}/manage/system/{service}/rivusitesetting.html?msgcode=E_MANAGE_70010002");
		}
		return super.request(response, orgi);
	}
	
	
	@RequestMapping(value = "/rivusitesettingedit/{id}", name = "rivusitesettingedit", type = "manage", subtype = "system")
	public ModelAndView rivusitesettingedit(HttpServletRequest request,
			@PathVariable String orgi,@PathVariable String id,@PathVariable String service) throws Exception{
		ResponseData responseData = new ResponseData("/pages/manage/system/rivusitesettingedit") ; 
		RivuSite rivesite = (RivuSite) super.getService().getIObjectByPK(RivuSite.class,id);
		if(service.equals("sms")){
			responseData = new ResponseData("/pages/manage/system/rivusitesmssettingedit") ; 
		}
    	ModelAndView view = request(responseData , orgi);
    	view.addObject("rivesite",rivesite);
    	view.addObject("type",service);
		return view;
	}
	
	@RequestMapping(value = "/rivusitesettingedito/{id}", name = "rivusitesettingedito", type = "manage", subtype = "system")
	public ModelAndView rivusitesettingedito(HttpServletRequest request,
			@PathVariable String orgi,@PathVariable String id,@Valid RivuSite rivusite) throws Exception {
		RivuSite rs = (RivuSite) super.getService().getIObjectByPK(RivuSite.class,id);
		ResponseData response = new ResponseData(
				"redirect:/{orgi}/manage/system/{service}/rivusitesetting.html");
		if (rs != null) {
			if(rivusite.getSmtppassword() != null && rivusite.getSmtppassword() != ""){
				rs.setSmtppassword(RivuTools.encryption(rivusite.getSmtppassword()));
			}
			rs.setSmtpserver(rivusite.getSmtpserver());;
			rs.setSmtpuser(rivusite.getSmtpuser());
			rs.setMailfrom(rivusite.getMailfrom());
			rs.setSeclev(rivusite.getSeclev());
			super.getService().saveOrUpdateIObject(rs);
		}
		return super.request(response, orgi);
	}
	
	
	@RequestMapping(value = "/rivusitesettingdel/{id}", name = "rivusitesettingdel", type = "manage", subtype = "system")
	public ModelAndView rivusitesettingdel(HttpServletRequest request,
			@PathVariable String orgi,@PathVariable String id) throws Exception {
		RivuSite rivusite = (RivuSite) super.getService().getIObjectByPK(RivuSite.class,id);
		ResponseData response = new ResponseData(
				"redirect:/{orgi}/manage/system/{service}/rivusitesetting.html");
		if (rivusite != null) {
			super.getService().deleteIObject(rivusite);
		}
		return super.request(response, orgi);
	}
	
	/**
	 * 测试邮件服务器是否畅通
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/rivusitesettingtest/{id}", name = "rivusitesettingtest", type = "manage", subtype = "system")
	public ModelAndView rivusitesettingtest(HttpServletRequest request,
			@PathVariable String orgi,@PathVariable String id) throws Exception{
		//获取到该邮件的信息
		RivuSite rivusite = (RivuSite) super.getService().getIObjectByPK(RivuSite.class,id);
		ResponseData responseData = new ResponseData("/pages/manage/system/loadurl_result" , orgi);
		String result = LocalTools.getMessage("S_MSG_80030001");
		try {
			MailSender sender = new MailSender(rivusite.getSmtpserver() ,rivusite.getMailfrom(), rivusite.getSmtpuser(), RivuTools.decryption(rivusite.getSmtppassword()));
			sender.send(rivusite.getMailfrom(), LocalTools.getMessage("MSG_80030003"), RivuTools.getTemplet((SearchResultTemplet) RivuDataContext.getService().getIObjectByPK(SearchResultTemplet.class, "402881e43ab07e65013ab080e4c60001"), new HashMap()));
		} catch (Exception e) {
			e.printStackTrace();
			result = LocalTools.getMessage("E_MSG_80030002");
		}
		ModelAndView view = request(responseData,orgi) ;
		view.addObject("result_msg",result);
		return view;
	}
	

}
